package com.pilipala.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pilipala.constant.MessageConstant;
import com.pilipala.constant.UploadConstant;
import com.pilipala.context.BaseContext;
import com.pilipala.dto.CommentAddDTO;
import com.pilipala.dto.CommentChildDTO;
import com.pilipala.dto.CommentDTO;
import com.pilipala.entity.Blog;
import com.pilipala.entity.Comment;
import com.pilipala.entity.User;
import com.pilipala.entity.Video;
import com.pilipala.exception.CommentException;
import com.pilipala.exception.DeleteException;
import com.pilipala.mapper.BlogMapper;
import com.pilipala.mapper.CommentMapper;
import com.pilipala.mapper.UserMapper;
import com.pilipala.mapper.VideoMapper;
import com.pilipala.result.PageResult;
import com.pilipala.service.CommentService;
import com.pilipala.utils.AliOssUtil;
import com.pilipala.vo.BlogVO;
import com.pilipala.vo.CommentVO;
import com.pilipala.vo.VideoVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private VideoMapper videoMapper;

    @Autowired
    private BlogMapper blogMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AliOssUtil aliOssUtil;
    /**
     * 批量列出评论
     * @param commentDTO 被评论类的Id、页码、页大小获取评论
     * @return 分页后的  --基础的评论字段和评论人的头像
     */
    @Override
    public PageResult getByMetaId(CommentDTO commentDTO) {
        PageHelper.startPage(commentDTO.getPage(),commentDTO.getSize());
        Page<Comment> page = commentMapper.getByMetaId(commentDTO);

        long total = page.getTotal();
        List<Comment> commentList = page.getResult();
        List<CommentVO> commentVOList = new ArrayList<>();
        for (var item : commentList){
            String contentPath = item.getContentPath();
            String objectName = contentPath.substring(contentPath.lastIndexOf("/")+1);
            String content = aliOssUtil.get(UploadConstant.COMMENT_PRE + objectName);

            CommentVO commentVO = new CommentVO();
            BeanUtils.copyProperties(item,commentVO);
            commentVO.setContent(content);

            Integer children = commentMapper.countChild(item.getId());
            commentVO.setChildren(children);

//            获取到发送评论的用户信息
            User user = userMapper.getUserById(commentVO.getPostUserId());
            commentVO.setAvatarPath(user.getAvatarPath());
            commentVOList.add(commentVO);
        }
        return new PageResult(total,commentVOList);
    }


    /**
     * 添加评论
     * @param commentAddDTO videoId、blogId,contentId
     */
    @Override
    public void add(CommentAddDTO commentAddDTO) {
        String content = commentAddDTO.getContent();
        if (content == null){
            throw new CommentException(MessageConstant.CONTENT_ERROR);
        }
//        上传评论文件
        String commentPath = aliOssUtil.upload(content.getBytes(StandardCharsets.UTF_8), UploadConstant.COMMENT_PRE
                + UUID.randomUUID() + "." + UploadConstant.COMMENT_EXTENSION);
//        增加被评论类的评论数
        if (commentAddDTO.getBlogId() != null){
            blogMapper.incrementComment(commentAddDTO.getBlogId());
        }
        else if (commentAddDTO.getVideoId() != null){
            videoMapper.incrementComment(commentAddDTO.getVideoId());
        }
//        获取到post的user
        User postUser = userMapper.getUserById(BaseContext.getCurrentId());
        User getUser = null;
        if (commentAddDTO.getGetUserId() != null){
            getUser = userMapper.getUserById(commentAddDTO.getGetUserId());
        }
        Comment comment = Comment.builder()
                .contentPath(commentPath)
                .likes(0)
                .postUserId(BaseContext.getCurrentId())
                .postUserName(postUser.getUserName())
                .subCommitId(commentAddDTO.getSubCommitId())
                .videoId(commentAddDTO.getVideoId())
                .blogId(commentAddDTO.getBlogId())
                .time(new Date()).build();
        if (getUser != null){
            comment.setGetUserId(getUser.getId());
            comment.setGetUserName(getUser.getUserName());
        }
        if (commentAddDTO.getSubCommitId() == null){
            comment.setSubCommitId(0L);
        }
        commentMapper.add(comment);
    }

    /**
     * 获取子评论
     * @param commentChildDTO 页码、页数、媒体id、父评论id
     * @return 返回分页后的结果
     */
    @Override
    public PageResult listChild(CommentChildDTO commentChildDTO) {
        PageHelper.startPage(commentChildDTO.getPage(),commentChildDTO.getSize());
        Page<Comment> page = commentMapper.listChild(commentChildDTO);

        long total = page.getTotal();
        List<Comment> commentList = page.getResult();
        List<CommentVO> commentVOList = new ArrayList<>();
        for (var item : commentList){
            String contentPath = item.getContentPath();
            String objectName = contentPath.substring(contentPath.lastIndexOf("/") + 1);
            String content = aliOssUtil.get(UploadConstant.COMMENT_PRE + objectName);

            CommentVO commentVO = new CommentVO();
            BeanUtils.copyProperties(item,commentVO);
            commentVO.setContent(content);

//            获取到发送评论的用户信息
            User user = userMapper.getUserById(commentVO.getPostUserId());
            commentVO.setAvatarPath(user.getAvatarPath());
            commentVOList.add(commentVO);
        }
        page.close();
        PageHelper.clearPage();
        return new PageResult(total,commentVOList);
    }

    /**
     * 删除评论
     * @param id 评论Id
     */
    @Override
    public void deleteItem(Long id) {
        Comment comment = commentMapper.getById(id);
        if (!comment.getPostUserId().equals(BaseContext.getCurrentId())){
//            只有本人能删
            throw new DeleteException(MessageConstant.POWER_ERROR);
        }

        Integer childNum = commentMapper.countChild(id);
//        删除父评论
        commentMapper.deleteSubComment(id);
//        删除子评论
        commentMapper.deleteChild(id);

        if (comment.getVideoId() != null){
            Video videoVO = videoMapper.getById(comment.getVideoId());
            Video video = new Video();
            BeanUtils.copyProperties(videoVO,video);
//            减掉被删除的评论个数
            video.setCommitNumber(video.getCommitNumber() - childNum - 1);
            videoMapper.update(video);
        }
        if (comment.getBlogId() != null){
            BlogVO blogVO = blogMapper.getById(comment.getBlogId());
            Blog blog = new Blog();
            BeanUtils.copyProperties(blogVO,blog);
//            减掉被删除的评论个数
            blog.setCommitNumber(blog.getCommitNumber() - childNum - 1);
            blogMapper.update(blog);
        }
    }

    @Override
    public void deleteChild(Long id) {
        Comment comment = commentMapper.getById(id);
        if (!comment.getPostUserId().equals(BaseContext.getCurrentId())){
//            只有本人能删
            throw new DeleteException(MessageConstant.POWER_ERROR);
        }
//        删除父评论
        commentMapper.deleteSubComment(id);
        if (comment.getVideoId() != null){
            Video videoVO = videoMapper.getById(comment.getVideoId());
            Video video = new Video();
            BeanUtils.copyProperties(videoVO,video);
//            减掉被删除的评论个数
            video.setCommitNumber(video.getCommitNumber() - 1);
            videoMapper.update(video);
        }
        if (comment.getBlogId() != null){
            BlogVO blogVO = blogMapper.getById(comment.getBlogId());
            Blog blog = new Blog();
            BeanUtils.copyProperties(blogVO,blog);
//            减掉被删除的评论个数
            blog.setCommitNumber(blog.getCommitNumber() - 1);
            blogMapper.update(blog);
        }
    }


}
